package zouran.filepractice.service;

import org.junit.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;

/**
 * Author：zouran
 * Date：2023/4/29  23:33
 */
public class TxtRead {
    //resources下的相对路径
    public final String relativeUrl="\\study\\1.txt";
    //拼接文件读取路径
    public final String fileUrl=new File(Objects.requireNonNull(this.getClass().getResource("/")).getPath()+relativeUrl).getPath();
    //    public  final String fileUrl="D:\\1.txt";
    @Test
    public void text() throws IOException {
        write_1();
        read_1();
        read_2();
    }
    //读取text
    public  void read_1() throws IOException {

        File file=new File(fileUrl);
        if(!file.exists()){
            System.out.println(file.getName()+"文件不存在");
        }
        InputStream inputStream=new FileInputStream(file);
        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
        String line;
        while ((line= bufferedReader.readLine())!=null)
        {
            System.out.println(line);
        }
        bufferedReader.close();
    }
    //读取text
    public  void read_2() throws IOException {
        List<String> list= Files.readAllLines(Path.of(fileUrl));
        for (String s : list) {
            System.out.println(s);
        }
    }
    //写入text
    public  void write_1() throws IOException {
       OutputStream outputStream=new FileOutputStream(fileUrl,true);
       String s="hello";
       byte[] bytes=s.getBytes(StandardCharsets.UTF_8);
       outputStream.write(bytes,0,bytes.length);
       outputStream.close();
    }
}
